const CryptoJS = require('./crypto-js')
const fs = require('fs')
const path = require('path')

const {hashRsaPsw} = require('./enc')
  // targetPath: string,
  // output: string,
  // psw: string,
  // fileName: string,
  // billPath: string,
  // encConfigFile?: string // 加密配置文件[投标]，  招标不传
const encryptoECB = (filePath, output, fileName, key, enckey, version ) => {
  try {
    const outputTmpFile = path.resolve(output, 'encing.zbd')
    const outputFileName = path.resolve(output, fileName)
    // 加密文件串
    const fileStr = fs.readFileSync(filePath, 'utf-8')
    let srcs = fileStr
    // 加密密文
    const paramsKEY = CryptoJS.enc.Utf8.parse(key)
    console.log('EncryptECB....文件字符串转义ok', output)
    console.log('EncryptECB....开始循环加密')
    const step = 2000000
    console.log('EncryptECB...步长' + step)
    const srclength = srcs.length
    console.log('EncryptECB...srcs.length' + srclength)
    let k = 0
    fs.writeFileSync(outputTmpFile, '', 'utf-8')
    for (let i = 0; (i + 1) * step < srclength; i++) {
      console.log('EncryptECB...i=' + i)
      const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(srcs.substring(0, step)), paramsKEY, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      })
      const result = CryptoJS.enc.Base64.stringify(
        CryptoJS.enc.Hex.parse(encrypted.ciphertext.toString().toUpperCase())
      )
      fs.appendFileSync(outputTmpFile, `${result}|||`, 'utf-8')
      //   fileArray.push(perfile)
      srcs = srcs.substring(step)
      k = i
      console.log(
        `progress:${(((srclength - srcs.length) / srclength) * 100).toFixed(0)}:${i === 0 ? 'start' : 'ing'}`
      )
    }
    console.log('EncryptECB...k=' + k)
    const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(srcs), paramsKEY, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    })
    const result = CryptoJS.enc.Base64.stringify(
      CryptoJS.enc.Hex.parse(encrypted.ciphertext.toString().toUpperCase())
    )
    fs.appendFileSync(outputTmpFile, `${result}|||`, 'utf-8')
    fs.appendFileSync(outputTmpFile, `{{{${enckey}}}}[[${version}]]`, 'utf-8')
    
    fs.renameSync(outputTmpFile, outputFileName)

    console.log('progress:100:done')
  } catch (err) {
    console.log(err)
  }
}

const {encryptedPsw, hash} = hashRsaPsw('123456')
encryptoECB(
  '/Users/jianyijianse/work/wf/my-projects/frontend_interview/code/encrypto-file/file/招标文件[1.1.0-release].json',
  '/Users/jianyijianse/work/wf/my-projects/frontend_interview/code/encrypto-file/file',
  'pay0810.加密招标书',
  hash,
  encryptedPsw,
  '1.0.0'
)
